% Compute the global solution using a paramerized expectations algorithm
% Dynamic bank run model
% Bank leverage choice only
% Capital depreciation shock

close all
warning off

load('policy_tau_5_always')

%% Generate random shocks

options = optimset;
T = 100000;               % simulation periods
t_drop = 1000;

rng(1)                   % same random shock 
shocks = normrnd(0,1,T+1,1);  % random shock
%Exi = zeros(T+1);  % stochastic steady state

kv   = zeros(T+1,1);
rbv  = zeros(T+1,1);
nv   = zeros(T+1,1);
xiv  = zeros(T+1,1);
hv   = zeros(T+1,1);
cv   = zeros(T+1,1);
yv   = zeros(T+1,1);
iv   = zeros(T+1,1);
lv   = zeros(T+1,1);
pibv = zeros(T+1,1);
runv = zeros(T+1,1);
rhseev = zeros(T+1,1);
rkhat  = zeros(T+1,1);
rkhats = zeros(T+1,1);
prv  = zeros(T+1,1);
av   = zeros(T+1,1);

erk_next       = zeros(T+1,1);
erk_next_unreg = zeros(T+1,1);
kv_unreg = zeros(T+1,1);
lv_unreg = zeros(T+1,1);

%% Simulation

pol1_t = 0;
pol2_t = 0;

kv(1)  = k_ss;
rbv(1) = rb_ss;
nv(1)  = n_ss;
lv(1)  = kv(1)/nv(1);
av(1)  = a_ss;

    for t=2:T+1
        av(t) = rho_a*av(t-1) + sigma_a*shocks(t-1);
        hv(t)  = ((1-alpha)/psi*exp(av(t))*kv(t-1)^(alpha))^(1/(alpha+1/nu));
        yv(t)  = exp(av(t)) * kv(t-1)^(alpha)*hv(t)^(1-alpha);

        rkhats(t) = log ( rbv(t-1) * (1-1/lv(t-1)) * ( 1+lambda*(1-gamma) ) - (1-delta) );
        rkhat(t)  = log ( alpha*((1-alpha)/psi)^((1-alpha)/(alpha+1/nu)) ) ...
                  + (1+nu)/(alpha*nu+1)*av(t) - (1-alpha)/(alpha*nu+1)*log(kv(t-1));
        xiv(t)  = exp(rkhat(t))/exp(rkhats(t));

        K  = [kv(t-1) rbv(t-1) nv(t-1) xiv(t)];
        x0 = (log(K)).^expmx;
        x  = prod(x0,2)';
        if xiv(t) >= 1
            pibv(t)  = ( exp(rkhat(t)) + 1-delta )*lv(t-1)*nv(t-1) - rbv(t-1)*(lv(t-1)-1)*nv(t-1) - nv(t-1);

            if pibv(t) > 0
                rhseev(t) = exp(x*solved_eta1_rhsee);
                rbv(t)    = exp(x*solved_eta1_rbar);
                nv(t) = chi1*( chi0*pibv(t) + nv(t-1) ) + n0;
            else
                rhseev(t) = exp(x*solved_eta3_rhsee);
                rbv(t)    = exp(x*solved_eta3_rbar);
                nv(t) = chi1*(      pibv(t) + nv(t-1) ) + n0;
            end

        else
            pibv(t)  = ( exp(rkhat(t)) + 1-delta )*lv(t-1)*nv(t-1) - rbv(t-1)*(1+lambda*(1-gamma))*(lv(t-1)-1)*nv(t-1) - nv(t-1);
            nv(t) = n_ss*(1 - nd/100);
            rhseev(t) = exp(x*solved_eta2_rhsee);
            rbv(t)    = exp(x*solved_eta2_rbar);
            runv(t) = 1;
        end

        cv(t) = rhseev(t)^(-1) + psi*hv(t)^(1+1/nu)/(1+1/nu);
        iv(t) = yv(t) - cv(t);
        kv(t) = (1-delta)*kv(t-1) + iv(t);

        lv(t)  = kv(t)/nv(t);

        erk_next(t) = log ( alpha*((1-alpha)/psi)^((1-alpha)/(alpha+1/nu)) ) ...
                    + (1+nu)/(alpha*nu+1)*rho_a*av(t) - (1-alpha)/(alpha*nu+1)*log(kv(t));

        % check policy
        if pibv(t)>=thre_pib && nv(t)>thre_n
            
            lv_unreg(t) = lv(t)/(1-tau);
            kv_unreg(t) = lv_unreg(t)*nv(t);
            erk_next_unreg(t) = log ( alpha*((1-alpha)/psi)^((1-alpha)/(alpha+1/nu)) ) ...
                              + (1+nu)/(alpha*nu+1)*rho_a*av(t) - (1-alpha)/(alpha*nu+1)*log(kv_unreg(t));
            rbv(t) = fzero('func_Rb',rbv(t),options,lv_unreg(t),erk_next_unreg(t),lambda,gamma,delta,sigma_rk);

        else
            lv_unreg(t) = lv(t);
            kv_unreg(t) = kv(t);
            erk_next_unreg(t) = erk_next(t);
            rbv(t) = fzero('func_Rb',rbv(t),options,lv(t),erk_next(t),lambda,gamma,delta,sigma_rk);
        end

        rkhats_next = log ( rbv(t) * (1-1/lv(t)) * ( 1+lambda*(1-gamma) ) - (1-delta) );
        z_temp     = (rkhats_next - erk_next(t)) / sigma_rk;
        cdf = normcdf(z_temp);
        prv(t) = cdf;

    end
    % End of T period simulation

%% Pick up bank run events

window = 3;  % how many periods before and after runs to plot

% pick up all runV = 1

norun_num  = 0;
run_num    = 0;

sum_p_normal = 0;

rkhat_run  = zeros(1);
rkhats_run = zeros(1);
h_run   = zeros(1);
y_run   = zeros(1);
c_run   = zeros(1);
i_run   = zeros(1);
k_run   = zeros(1);
pib_run = zeros(1);
n_run   = zeros(1);
l_run   = zeros(1);
rb_run  = zeros(1);
pr_run  = zeros(1);
shock_run = zeros(1);
xi_run  = zeros(1);
tfp_run = zeros(1);

for t = t_drop:T-window

    if xiv(t) < 1

        run_num = run_num + 1;

        rkhat_run(run_num,1:1+2*window)  = rkhat(t-window:t+window);
        rkhats_run(run_num,1:1+2*window) = rkhats(t-window:t+window);
        h_run(run_num,1:1+2*window)   = hv(t-window:t+window);
        y_run(run_num,1:1+2*window)   = yv(t-window:t+window);
        c_run(run_num,1:1+2*window)   = cv(t-window:t+window);
        i_run(run_num,1:1+2*window)   = iv(t-window:t+window);
        k_run(run_num,1:1+2*window)   = kv(t-window:t+window);
        pib_run(run_num,1:1+2*window) = pibv(t-window:t+window);
        n_run(run_num,1:1+2*window)   = nv(t-window:t+window);
        l_run(run_num,1:1+2*window)   = lv(t-window:t+window);
        rb_run(run_num,1:1+2*window)  = rbv(t-window:t+window);
        pr_run(run_num,1:1+2*window)  = prv(t-window:t+window);
        shock_run(run_num,1:1+2*window) = shocks(t-window:t+window);
        tfp_run(run_num,1:1+2*window) = av(t-window:t+window);
        xi_run(run_num,1:1+2*window)  = xiv(t-window:t+window);

    else
        norun_num   = norun_num + 1;
    end

end

% BC moments
uncon_run_all_tau = run_num / (T-window-t_drop)
avg_y_all_tau  = mean(yv(t_drop:T));
avg_c_all_tau  = mean(cv(t_drop:T));
avg_h_all_tau  = mean(hv(t_drop:T));
avg_l_all_tau  = mean(lv(t_drop:T));
avg_n_all_tau  = mean(nv(t_drop:T));
avg_k_all_tau  = mean(kv(t_drop:T));
avg_pr_all_tau = mean(prv(t_drop:T));
avg_rb_all_tau = mean(rbv(t_drop:T));

std_y_all_tau  = std(yv(t_drop:T));
std_c_all_tau  = std(cv(t_drop:T));
std_h_all_tau  = std(hv(t_drop:T));
std_l_all_tau  = std(lv(t_drop:T));
std_n_all_tau  = std(nv(t_drop:T));
std_k_all_tau  = std(kv(t_drop:T));
std_pr_all_tau = std(prv(t_drop:T));
std_rb_all_tau = std(rbv(t_drop:T));

% run dynamics
run_avg_rkhat_tau  = mean(rkhat_run,1);
run_avg_rkhats_tau = mean(rkhats_run,1);
run_avg_h_tau   = mean(h_run,1);
run_avg_y_tau   = mean(y_run,1);
run_avg_c_tau   = mean(c_run,1);
run_avg_i_tau   = mean(i_run,1);
run_avg_k_tau   = mean(k_run,1);
run_avg_pib_tau = mean(pib_run,1);
run_avg_n_tau   = mean(n_run,1);
run_avg_l_tau   = mean(l_run,1);
run_avg_rb_tau  = mean(rb_run,1);
run_avg_pr_tau  = mean(pr_run,1);
run_avg_shock_tau = mean(shock_run,1);
run_avg_xi_tau  = mean(xi_run,1);
run_avg_tfp_tau = mean(tfp_run,1);

%% pick up runV = 1 and no run some periods before

norun_period = 12;
run_num2 = 0;

rkhat_run2 = zeros(1);
rkhats_run2  = zeros(1);
h_run2   = zeros(1);
y_run2   = zeros(1);
c_run2   = zeros(1);
i_run2   = zeros(1);
k_run2   = zeros(1);
pib_run2 = zeros(1);
n_run2   = zeros(1);
l_run2   = zeros(1);
rb_run2  = zeros(1);
pr_run2  = zeros(1);
shock_run2 = zeros(1);
tfp_run2 = zeros(1);
xi_run2  = zeros(1);

norm_num = 0;
norm_nega = 0;
norm_y   = zeros(1,1);
norm_c   = zeros(1,1);
norm_l   = zeros(1,1);
norm_k   = zeros(1,1);
norm_n   = zeros(1,1);
norm_pr  = zeros(1,1);
norm_rb  = zeros(1,1);
norm_h   = zeros(1,1);
norm_pib = zeros(1,1);
norm_posi_num = 0;

for t = t_drop:T-window

    if sum(runv(t-norun_period:t-1)) == 0
        
        if xiv(t) < 1

        run_num2 = run_num2 + 1;

        rkhat_run2(run_num2,1:1+2*window)  = rkhat(t-window:t+window);
        rkhats_run2(run_num2,1:1+2*window) = rkhats(t-window:t+window);
        h_run2(run_num2,1:1+2*window)   = hv(t-window:t+window);
        y_run2(run_num2,1:1+2*window)   = yv(t-window:t+window);
        c_run2(run_num2,1:1+2*window)   = cv(t-window:t+window);
        i_run2(run_num2,1:1+2*window)   = iv(t-window:t+window);
        k_run2(run_num2,1:1+2*window)   = kv(t-window:t+window);
        pib_run2(run_num2,1:1+2*window) = pibv(t-window:t+window);
        n_run2(run_num2,1:1+2*window)   = nv(t-window:t+window);
        l_run2(run_num2,1:1+2*window)   = lv(t-window:t+window);
        rb_run2(run_num2,1:1+2*window)  = rbv(t-window:t+window);
        pr_run2(run_num2,1:1+2*window)  = prv(t-window:t+window);
        shock_run2(run_num2,1:1+2*window) = shocks(t-window:t+window);
        tfp_run2(run_num2,1:1+2*window)  = av(t-window:t+window);
        xi_run2(run_num2,1:1+2*window)  = xiv(t-window:t+window);
        
        else
            
        norm_num = norm_num + 1;
        norm_y(norm_num)   = yv(t);
        norm_c(norm_num)   = cv(t);
        norm_l(norm_num)   = lv(t);
        norm_k(norm_num)   = kv(t);
        norm_n(norm_num)   = nv(t);
        norm_pr(norm_num)  = prv(t);
        norm_rb(norm_num)  = rbv(t);
        norm_h(norm_num)   = hv(t);
        norm_pib(norm_num) = pibv(t);

        if pibv(t) < 0
            norm_nega = norm_nega+1;
        else
            norm_posi_num = norm_posi_num + 1;
        end
        
        end
    end
end

run_norun_before_tau = run_num2 / (T-window-t_drop)

run2_avg_rkhat_pol  = mean(rkhat_run2,1);
run2_avg_rkhats_pol = mean(rkhats_run2,1);
run2_avg_h_pol   = mean(h_run2,1);
run2_avg_y_pol   = mean(y_run2,1);
run2_avg_c_pol   = mean(c_run2,1);
run2_avg_i_pol   = mean(i_run2,1);
run2_avg_k_pol   = mean(k_run2,1);
run2_avg_pib_pol = mean(pib_run2,1);
run2_avg_n_pol   = mean(n_run2,1);
run2_avg_l_pol   = mean(l_run2,1);
run2_avg_rb_pol  = mean(rb_run2,1);
run2_avg_pr_pol  = mean(pr_run2,1);
run2_avg_shock_pol = mean(shock_run2,1);
run2_avg_tfp_pol = mean(tfp_run2,1);
run2_avg_xi_pol  = mean(xi_run2,1);

norm_y_avg_tau   = mean(norm_y);
norm_c_avg_tau   = mean(norm_c);
norm_l_avg_tau   = mean(norm_l);
norm_k_avg_tau   = mean(norm_k);
norm_n_avg_tau   = mean(norm_n);
norm_pr_avg_tau  = mean(norm_pr);
norm_rb_avg_tau  = mean(norm_rb);
norm_h_avg_tau   = mean(norm_h);
norm_pib_avg_tau = mean(norm_pib);

nega_prob_tau = norm_nega/norm_num;

%% clear large data

clear shocks kv rbv nv xiv hv cv yv iv lv pibv runv rhseev rkhat rkhats prv av erk x x_nonlog x_allnonlog dv erk_next erk_next_unreg kv_unreg lv_unreg
clear rkhat_run rkhats_run h_run y_run c_run i_run k_run pib_run n_run l_run rb_run pr_run shock_run xi_run tfp_run pibv_nega nv_nega
clear rkhat_run2 rkhats_run2 h_run2 y_run2 c_run2 i_run2 k_run2 pib_run2 n_run2 l_run2 rb_run2 pr_run2 shock_run2 tfp_run2 xi_run2 d_run2
clear norm_y norm_c norm_l norm_k norm_i norm_n norm_pr norm_rb norm_h norm_pib norm_l_posi norm_d norm_rkhat
clear rhsee_derived_temp rbar_derived rbar_gap

return

figure

subplot(2,3,1)
histogram(lv(t_drop:T),'Normalization','probability')
hold on
plot([l_stss_nopol,l_stss_nopol],ylim,'r--','Linewidth',3);
%hold on
%plot([thre_l,thre_l],ylim,'k:','Linewidth',3);
set(gca,'FontSize',20);
grid on
title({'leverage','all time'})

subplot(2,3,2)
histogram(nv(t_drop:T),'Normalization','probability')
hold on
plot([n_stss_nopol,n_stss_nopol],ylim,'r--','Linewidth',3);
%hold on
%plot([thre_n,thre_n],ylim,'k:','Linewidth',3);
set(gca,'FontSize',20);
title({'net worth','all time'})

subplot(2,3,3)
histogram(rbv(t_drop:T),'Normalization','probability')
hold on
plot([rb_stss_nopol,rb_stss_nopol],ylim,'r--','Linewidth',3);
set(gca,'FontSize',20);
title({'deposit rate','all time'})

subplot(2,3,4)
histogram(norm_l,'Normalization','probability')
hold on
plot([l_stss_nopol,l_stss_nopol],ylim,'r--','Linewidth',3);
%hold on
%plot([thre_l,thre_l],ylim,'k:','Linewidth',3);
set(gca,'FontSize',20);
grid on
title({'leverage',['no run for ',num2str(norun_period),' periods']})

subplot(2,3,5)
histogram(norm_n,'Normalization','probability')
hold on
plot([n_stss_nopol,n_stss_nopol],ylim,'r--','Linewidth',3);
%hold on
%plot([thre_n,thre_n],ylim,'k:','Linewidth',3);
set(gca,'FontSize',20);
title({'net worth',['no run for ',num2str(norun_period),' periods']})

subplot(2,3,6)
histogram(norm_rb,'Normalization','probability')
hold on
plot([rb_stss_nopol,rb_stss_nopol],ylim,'r--','Linewidth',3);
set(gca,'FontSize',20);
title({'deposit rate',['no run for ',num2str(norun_period),' periods']})
